package br.com.social.mobile.servlet;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUpload;

import br.com.social.mobile.dao.ParameterDAO;
import br.com.social.mobile.entities.Parameter;
import br.com.social.mobile.util.IConstants;
import br.com.social.mobile.util.ImageWatermark;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try { 
		boolean isMultipart = FileUpload.isMultipartContent(request);    
		String path = pathImage(request);
		HttpSession session = request.getSession();
		
	       if (isMultipart) {    
	    	   String key = (String) session.getAttribute("KEY_REGISTER");
	    	   
	    	   // Create a new file upload handler    
	          DiskFileUpload upload = new DiskFileUpload();    
	              
	          // Set upload parameters    
	          upload.setSizeMax(50*1024*1024); //50Mb    
	          upload.setRepositoryPath(path);    
	              
	          // Parse the request    
	          List<?> items = upload.parseRequest(request);    
	              
	          Iterator<?> it = items.iterator();    
	          
	          while (it.hasNext()) {    
	        	  	FileItem fitem = (FileItem) it.next();    
					File uploadedFile = new File(path,fitem.getName());
					fitem.write(uploadedFile);
					BufferedImage image = ImageIO.read(uploadedFile);
					ImageWatermark.saveImages(image, key);
					uploadedFile.delete();
	             }    
	          }    
	       
	       
	       
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   	       
	}

	private String pathImage(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String path = "";
		if (session.getAttribute(IConstants.PARAMETER.PATH_SAVE_IMAGE) == null) {
			ParameterDAO dao = new ParameterDAO();
			dao.forceOpenConnection();				
			Parameter parameter = dao.findByParamName(IConstants.PARAMETER.PATH_SAVE_IMAGE);
			path = parameter.getDsParamValue();
			session.setAttribute(IConstants.PARAMETER.PATH_SAVE_IMAGE, path);
		} else {
			path = (String) session.getAttribute(IConstants.PARAMETER.PATH_SAVE_IMAGE);
		}
		
		return path;
	}
	
}